package org.abratuhi.kvngroupware.jokemanager.mptua;

import org.abratuhi.kvngroupware.jokemanager.manager.JokeManager;
import org.abratuhi.kvngroupware.jokemanager.model.Joke;
import org.abratuhi.kvngroupware.network.AbstractRequestMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.server.db.ServerDB;
import org.abratuhi.kvngroupware.user.manager.UserManager;
import org.jdom.Element;

public class JokemanagerRequestMessageProceeder extends AbstractRequestMessageProceeder{

	MessageSender sender;
	UserManager usermanager;
	JokeManager jokemanager;
	ServerDB db;

	public JokemanagerRequestMessageProceeder(MessageSender sender, UserManager usermanager, JokeManager jokemanager, ServerDB db){
		this.sender = sender;
		this.usermanager = usermanager;
		this.jokemanager = jokemanager;
		this.db = db;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element request = message.getRoot().getChild("request");
		String type = request.getAttributeValue("type");
		String action = request.getAttributeValue("action");

		if(type.equals("joke")){
			String teamId = request.getAttributeValue("teamId");
			String userId = request.getAttributeValue("userId");
			String jokeId = request.getAttributeValue("jokeId");
			Joke j = (request.getChildren().size() > 0 ) ? Joke.fromElement(request.getChild("joke")) : null;

			String[] attrNames = new String[]{"type", "action", "userId", "teamId", "jokeId", "status"};
			String[] attrValues= new String[]{type, action, userId, teamId, jokeId, "ok"};
			String text = new String();
			Element[] content = new Element[0];
			Message responseMessage;
			
			if(action.equals("create")){
				//content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
				//for(int i=0; i<content.length; i++) kvnserver.getDB().addJoke(content[i]);
				db.addJoke(j.toElement());
				content = new Element[]{j.toElement()};
			}
			else if(action.equals("get")){
				content = db.getJokes(userId, teamId);
			}
			else if(action.equals("update")){
				//content = (Element[]) request.removeContent().toArray(new Element[request.getContentSize()]);
				//for(int i=0; i<content.length; i++) kvnserver.getDB().updateJoke(content[i]);
				db.updateJoke(j.toElement());
				content = new Element[]{j.toElement()};
			}
			else if(action.equals("delete")){
				// TODO
				db.removeJoke(j.toElement());
				content = new Element[]{j.toElement()};
			}

			responseMessage = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(responseMessage);

		}
	}

}
